package mqtt

import (
	"encoding/json"
	"fmt"
	"log"
	"strings"
	"time"

	"things_iot_backend/auth"
	"things_iot_backend/cache"
	"things_iot_backend/config"
	"things_iot_backend/database"
	"things_iot_backend/models"
)

// MQTTServer 简化的MQTT服务器实现
type MQTTServer struct {
	cfg *config.Config
}

func NewMQTTServer(cfg *config.Config) *MQTTServer {
	return &MQTTServer{
		cfg: cfg,
	}
}

func (m *MQTTServer) Start() error {
	log.Printf("MQTT server configured for TCP port %d and WebSocket port %d", m.cfg.MQTTPort, m.cfg.MQTTWSPort)
	log.Println("Note: This is a simplified implementation. For full MQTT functionality, integrate with a proper MQTT broker.")
	return nil
}

func (m *MQTTServer) Stop() error {
	log.Println("MQTT server stopped")
	return nil
}

// ProcessDeviceMessage 处理设备消息（模拟MQTT消息处理）
func (m *MQTTServer) ProcessDeviceMessage(deviceID string, topic string, payload []byte) error {
	// 获取设备信息
	var device models.Device
	if err := database.DB.Where("device_id = ?", deviceID).First(&device).Error; err != nil {
		return fmt.Errorf("device not found: %s", deviceID)
	}

	// 根据主题类型处理消息
	switch {
	case strings.HasSuffix(topic, "/telemetry"):
		return m.handleTelemetryMessage(device, payload)
	case strings.HasSuffix(topic, "/status"):
		return m.handleStatusMessage(device, payload)
	case strings.HasSuffix(topic, "/events"):
		return m.handleEventMessage(device, payload)
	case strings.HasSuffix(topic, "/command/response"):
		return m.handleCommandResponse(device, payload)
	default:
		return fmt.Errorf("unknown topic: %s", topic)
	}
}

func (m *MQTTServer) handleTelemetryMessage(device models.Device, payload []byte) error {
	var telemetryPayload models.MQTTTelemetryPayload
	if err := json.Unmarshal(payload, &telemetryPayload); err != nil {
		return fmt.Errorf("failed to parse telemetry payload: %v", err)
	}

	// 解析时间戳
	timestamp, err := time.Parse(time.RFC3339, telemetryPayload.Timestamp)
	if err != nil {
		timestamp = time.Now()
	}

	// 创建完整的遥测数据JSON
	telemetryData := make(models.JSONB)

	// 添加主设备指标
	for k, v := range telemetryPayload.Metrics {
		telemetryData[k] = v
	}

	// 添加子设备数据（如果存在）
	if device.DeviceType == "gateway" && telemetryPayload.Subdevices != nil {
		telemetryData["subdevices"] = telemetryPayload.Subdevices
	}

	// 插入遥测数据
	telemetry := &models.DeviceTelemetry{
		Time:          timestamp,
		DeviceID:      device.ID,
		TelemetryData: telemetryData,
	}

	if err := database.InsertTelemetryData(telemetry); err != nil {
		log.Printf("Failed to insert telemetry data: %v", err)
	}

	// 缓存最新数据
	latestData := make(map[string]interface{})
	for k, v := range telemetryPayload.Metrics {
		latestData[k] = v
	}
	if err := cache.CacheDeviceLatestData(device.ID, latestData); err != nil {
		log.Printf("Failed to cache latest data: %v", err)
	}

	log.Printf("Processed telemetry data for device %s", device.DeviceID)
	return nil
}

func (m *MQTTServer) handleStatusMessage(device models.Device, payload []byte) error {
	var statusPayload models.MQTTStatusPayload
	if err := json.Unmarshal(payload, &statusPayload); err != nil {
		return fmt.Errorf("failed to parse status payload: %v", err)
	}

	// 更新设备状态
	updates := map[string]interface{}{
		"status":    statusPayload.Status,
		"last_seen": time.Now(),
	}

	if err := database.DB.Model(&device).Updates(updates).Error; err != nil {
		log.Printf("Failed to update device status: %v", err)
	}

	// 缓存设备状态
	if err := cache.CacheDeviceStatus(device.ID, statusPayload.Status); err != nil {
		log.Printf("Failed to cache device status: %v", err)
	}

	log.Printf("Updated status for device %s to %s", device.DeviceID, statusPayload.Status)
	return nil
}

func (m *MQTTServer) handleEventMessage(device models.Device, payload []byte) error {
	var eventPayload models.MQTTEventPayload
	if err := json.Unmarshal(payload, &eventPayload); err != nil {
		return fmt.Errorf("failed to parse event payload: %v", err)
	}

	// 解析时间戳
	timestamp, err := time.Parse(time.RFC3339, eventPayload.Timestamp)
	if err != nil {
		timestamp = time.Now()
	}

	event := &models.DeviceEvent{
		Time:      timestamp,
		DeviceID:  device.ID,
		EventType: eventPayload.EventType,
		EventData: models.JSONB(eventPayload.EventData),
		CreatedAt: time.Now(),
	}

	if err := database.InsertEventData(event); err != nil {
		log.Printf("Failed to insert event data: %v", err)
	}

	log.Printf("Recorded %s event for device %s", eventPayload.EventType, device.DeviceID)
	return nil
}

func (m *MQTTServer) handleCommandResponse(device models.Device, payload []byte) error {
	var responsePayload models.MQTTCommandResponsePayload
	if err := json.Unmarshal(payload, &responsePayload); err != nil {
		return fmt.Errorf("failed to parse command response: %v", err)
	}

	log.Printf("Received command response for device %s: %s", device.DeviceID, responsePayload.Status)
	// 这里可以进一步处理命令响应，比如更新命令状态等
	return nil
}

// PublishCommand 发布命令到设备（模拟MQTT发布）
func PublishCommand(device models.Device, command models.MQTTCommandPayload) error {
	log.Printf("Publishing command to device %s: %s", device.DeviceID, command.Command)
	// 在实际实现中，这里会通过MQTT协议发布消息到设备
	return nil
}

// VerifyDeviceCredentials 验证设备MQTT凭证
func VerifyDeviceCredentials(deviceID, username, password, secretKey string) bool {
	// 验证用户名格式
	expectedUsername := fmt.Sprintf("things_iot_%s", deviceID)
	if username != expectedUsername {
		return false
	}

	// 验证密码
	expectedPassword, err := auth.GenerateMQTTPassword(deviceID, username, secretKey)
	if err != nil {
		return false
	}
	return password == expectedPassword
}
